package com.region.spring.resolver;

import com.region.common.utils.RandomUtils;
import com.region.common.utils.ReflectUtils;
import com.region.http.client.model.ResponseData;
import com.region.http.client.resolver.result.AbstractResultResolver;
import com.region.spring.part.RegionSpringMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;

/**
 * @author 26225
 * @date 2024/7/21 10:47
 * @description
 */
public class MultipartFileResultResolver extends AbstractResultResolver {

    @Override
    public boolean isResolver(Type type) {
        Class<?> returnClass = ReflectUtils.transform(type);
        return MultipartFile.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(ResponseData responseData) throws Throwable {
        String headerName = "Content-Disposition";
        ResponseData.NameValuePair[] nameValuePairs = responseData.getNameValuePairs().get(headerName);
        String fileName = null;
        for (ResponseData.NameValuePair nameValuePair : nameValuePairs) {
            if ("filename".equals(nameValuePair.getName())) {
                fileName = nameValuePair.getValue();
                break;
            }
        }
        if (fileName == null) {
            fileName = RandomUtils.getId();
        }
        return new RegionSpringMultipartFile(fileName, fileName, null, responseData.getBody());
    }

    @Override
    public int getPriority() {
        return 15;
    }
}
